<template>
  <!-- 页面-值集管理-设置 -->
  <div class="innerPageTable-box-Four VDefineSelf-page innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="formSearch"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 值集编码 -->
          <Form-item :label="this.$t('module.valueSet.vsCode')">
            <Input type="text" v-model.trim="formSearch.vsCode" disabled></Input>
          </Form-item>

          <!-- 值集名称 -->
          <Form-item :label="this.$t('module.valueSet.vsName')">
            <Input type="text" v-model.trim="formSearch.vsName" disabled></Input>
          </Form-item>

          <!-- 值集类型 -->
          <Form-item :label="this.$t('module.valueSet.vsType')">
            <Input type="text" v-model.trim="formSearch.vsType" disabled></Input>
          </Form-item>

          <!-- 值来源 -->
          <Form-item :label="this.$t('module.valueSet.vsValueSource')">
            <Input type="text" v-model.trim="formSearch.vsValueSources" disabled></Input>
          </Form-item>

          <!-- 父值集 -->
          <Form-item :label="this.$t('module.valueSet.parentVs')">
            <Input type="text" v-model.trim="formSearch.vsParentName" disabled></Input>
          </Form-item>

          <!-- 所属租户 -->
          <Form-item :label="this.$t('module.valueSet.ownnerTenant')">
            <Input type="text" v-model.trim="formSearch.tenantName" disabled></Input>
          </Form-item>

          <!-- 状态 -->
          <Form-item :label="this.$t('common.status')">
            <Input type="text" v-model.trim="formSearch.enabled" disabled></Input>
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>

    <InnerPageTable
      ref="vDefineTable"
      action="VSelfDefineList"
      :columns="tableColumns"
      :config="pageTableConfig"
    >
      <!-- <Form
        :model="formSearch"
        slot="search-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <Row :gutter="16">
            
          </Row>
        </template>
      </Form>-->

      <!-- <Form :model="formSearch" slot="search-bar" label-position="top" class="ivu-form-no-margin-bottom" inline>
      </Form>-->
      <div slot="table-bar">
        <RPButton optType="create" v-if="isEdit && isShow" @click="addOrUpdateVDefineSelf" />
        <!-- <OptionRight resourceCode="dict_item_del">
          <RPButton optType="delete" v-if="false" @click="deleteDimension" />
        </OptionRight>-->
      </div>
    </InnerPageTable>
  </div>
</template>
<script>
import AddOrUpdateVDefineSelf from "./AddOrUpdateVDefineSelf.vue";
import valueSet from "@lang/modules/valueSet";
import tenantManage from "@lang/modules/tenantManage";
import tenantAPI from "@/api/tenantApi.js";

export default {
  components: {},
  locales: {
    "zh-CN": {
      module: {
        valueSet: valueSet["zh-CN"],
        tenantManage: tenantManage["zh-CN"]
      }
    },
    "en-US": {
      module: {
        valueSet: valueSet["en-US"],
        tenantManage: tenantManage["en-US"]
      }
    }
  },
  props: {
    vsType: {
      type: Number,
      default() {
        return 0;
      }
    },
    isEdit: {
      type: Boolean,
      default() {
        return false;
      }
    },
    vsId: {
      type: String,
      default() {
        return "";
      }
    },
    vsCode: {
      type: String,
      default() {
        return "";
      }
    },
    columnType: [String, Number],
    tenantCode: {
      type: String,
      default() {
        return "";
      }
    },
    vsValueSource: {
      type: Number,
      default: 2
    },
    ownnerTenant: {
      type: String,
      default() {
        return "";
      }
    },
    tenantId: {
      type: String,
      default() {
        return "";
      }
    },
    source: {
      type: Number,
      default() {
        return "";
      }
    }
  },
  data() {
    return {
      productData: [],
      // tenantList: [],
      formSearch: {
        vsCode: "",
        vsName: "",
        orgName: "",
        vsParentCode: "",
        vsParentName: "",
        tenantName: "",
        vsType: "",
        enabled: "",
        vsValueSources: ""
      },
      editLoading: false,
      //   tableColumns: [],
      ownnerTenantName: "", // 租户名称
      pageTableConfig: {
        columnsFn: this.tableColumns,
        loadDataFn: this.VSelfDefineList,
        autoFirst: false,
        initParam: { vsCode: this.vsCode, tenantCode: this.tenantCode }
      },
      parentValueList: {}
    };
  },
  created: function() {
    $http.get(`${window.RPConfig.setting}/valueset/view?valueSetId=${this.vsId}`).then(response => {
      response = response.data;
      this.formSearch.vsCode = response.vsCode;
      this.formSearch.vsName = response.vsName;
      this.formSearch.vsType =
        response.vsType == "1" ? this.$t("module.valueSet.independent") : this.$t("module.valueSet.subordinate");
      this.formSearch.vsParentCode = response.vsParentCode;
      this.formSearch.vsParentName = response.vsParentName;
      this.formSearch.orgName = response.orgName;
      this.formSearch.enabled = response.enabled == "1" ? this.$t("common.valid") : this.$t("common.invalid");
      this.formSearch.productCode = response.productCode;
      // this.formSearch.productName = this.getProductName(this.formSearch.productCode);
      this.formSearch.tenantName = response.tenantName;
      this.formSearch.vsValueSources = response.vsValueSource;
      if (response.vsValueSource == "1") {
        this.formSearch.vsValueSources = this.$t("module.valueSet.valueSourceItem.system");
      } else if (response.vsValueSource == "2") {
        this.formSearch.vsValueSources = this.$t("module.valueSet.valueSourceItem.scalable");
      } else if (response.vsValueSource == "3") {
        this.formSearch.vsValueSources = this.$t("module.valueSet.valueSourceItem.custom");
      } else if (response.vsValueSource == "4") {
        return (this.formSearch.vsValueSources = this.$t("module.valueSet.valueSourceItem.dynamic"));
      }
      // this.formSearch.publicFlag =
      //   response.publicFlag == "1" ? this.$t("module.valueSet.public") : this.$t("module.valueSet.notpublic");
      // 有父值集
      if (this.formSearch.vsParentName) {
        this.initParentValue();
      } else {
        this.search();
      }
    });

    this.getProductData();
    this.initTenant(); //获取租户编码对应的租户名称
    // console.log(this.ownnerTenant);
  },
  beforeMount: function() {},
  mounted: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
  computed: {
    isShow() {
      if (this.vsValueSource == 1 && this.source == 1) {
        return false;
      } else if (this.tenantId == window.RPConfig.rootTenantCode && this.vsValueSource == 1 && this.ownnerTenant != window.RPConfig.rootTenantCode) {
        return false;
      }
      return true;
    }
  },
  methods: {
    // 初始化所属租户,获取租户编码对应的租户名称
    initTenant() {
      tenantAPI.queryAllTenantList().then(data => {
        for (const tenant of data) {
          if (this.ownnerTenant == tenant.tenantCode) {
            this.ownnerTenantName = tenant.tenantName;
          }
        }
      });
    },
    getBaseColumns() {
      return [
        {
          title: this.$t("module.valueSet.valuecode"),
          align: "left",
          key: "vsiKey"
        },
        {
          title: this.$t("module.valueSet.value"),
          align: "left",
          key: "vsiValue"
        },
        {
          title: "所属租户",
          align: "left",
          key: "tenantName"
          // render: (h, params) => {
          //   console.log("params",params)
          //   return h(
          //     "div",
          //     {
          //       attrs: {
          //         class: "ivu-table-cell ivu-table-cell-ellipsis",
          //         title: params.row.tenantName
          //       }
          //     },
          //     params.row.updateTime
          //   );
          // }
        },
        {
          title: this.$t("module.valueSet.parentVs"),
          align: "left",
          key: "vsParentName"
        },
        {
          title: this.$t("common.sort"),
          align: "left",
          key: "sort"
        },
        {
          title: this.$t("module.valueSet.startDate"),
          align: "left",
          key: "vsiStartDate",
          render: (h, params) => {
            return h("format", {
              props: {
                type: "date",
                value: params.row.vsiStartDate,
                param: "yyyy-MM-dd"
              }
            });
          }
        },
        {
          title: this.$t("module.valueSet.endDate"),
          align: "left",
          key: "vsiEndDate",
          render: (h, params) => {
            return h("format", {
              props: {
                type: "date",
                value: params.row.vsiEndDate,
                param: "yyyy-MM-dd"
              }
            });
          }
        },

        {
          title: this.$t("common.status"),
          align: "left",
          key: "enabled",
          render: (h, params) => {
            return h(
              "StatusButton",
              {
                props: {
                  status: params.row.enabled == 1 ? "0" : "1"
                }
              },
              params.row.enabled == 1 ? this.$t("common.enable") : this.$t("common.disable")
            );
          }
        },
        {
          title: this.$t("common.operating"),
          align: "left",
          fixed: "right",
          width: 80,
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: this.getOperatingCols(params.row)
              },
              directives: [
                {
                  name: "show",
                  value: this.isEdit
                }
              ]
            });
          }
        }
      ];
    },
    tableColumns() {
      const baseColumns = this.getBaseColumns();
      if (this.columnType == "2") {
        return [
          ...baseColumns,
          {
            title: this.$t("module.valueSet.parentValue"),
            align: "left",
            key: "vsiParentValue"
          }
        ];
      } else {
        return baseColumns;
      }
    },
    search() {
      this.$refs["vDefineTable"].load();
    },

    VSelfDefineList({ responseProcess, param }) {
      $http.post(`${window.RPConfig.setting}/valueset/item/list/page`, param).then(({ data }) => {
        let { records } = data;
        records.forEach(item => {
          // item.tenantName = this.getTenantName(item.tenantCode);
          if (this.formSearch.vsParentName) {
            item.vsiParentValue = this.getParentValue(item.vsiParentKey);
          }
        });
        responseProcess(data);
      });
    },

    deleted(id) {
      new $confirm(this.$t("common.warning.confirmToDelete"), this).then(() => {
        $http.post(`${window.RPConfig.setting}/valueset/item/delete`, [id]).then(() => {
          this.$message.success({
            content: this.$t("common.deleteSuccess"),
            duration: 3
          });
          this.search();
        });
      });
    },
    // getProductName(code) {
    //   for (let item of this.productData) {
    //     if (code === item.vsiKey) {
    //       return item.vsiValue;
    //     }
    //   }
    //   return code;
    // },
    getProductData() {
      $http
        .get(`${window.RPConfig.setting}/valueset/item/list?vsCode=${"RC_PRODUCT"}`)
        .then(response => {
          this.productData = response.data;
        })
        .catch(error => {
          this.$message.error({
            content: error.message,
            duration: 3
          });
        });
    },
    // 初始化所属租户
    // initTenant() {
    //   tenantAPI.queryAllTenantList().then(data => {
    //     for (const tenant of data) {
    //       this.tenantList[tenant.tenantCode] = tenant.tenantName;
    //     }
    //   });
    // },
    // getTenantName(tenantCode) {
    //   if (tenantCode) {
    //     return this.tenantList[tenantCode] ? this.tenantList[tenantCode] : tenantCode;
    //   }
    //   return tenantCode;
    // },
    //获取父值
    initParentValue() {
      $http
        .get(`${window.RPConfig.setting}/valueset/item/list/parent?vsCode=` + this.formSearch.vsCode)
        .then(({ data }) => {
          this.search();
          for (const parent of data) {
            this.parentValueList[parent.vsiKey] = parent.vsiValue;
          }
        });
    },
    getParentValue(parentKey) {
      if (parentKey) {
        return this.parentValueList[parentKey] ? this.parentValueList[parentKey] : parentKey;
      }
      return parentKey;
    },
    addOrUpdateVDefineSelf(obj) {
      if (obj.id) {
        if(this.editLoading) {
          return false
        }
        this.editLoading = true	
        $http.get(`${window.RPConfig.setting}/valueset/item/lang/list?vsiId=${obj.id}`).then(res => {
          let _obj = JSON.parse(JSON.stringify(obj));
          _obj.vsiValue = res.data;
          this.editLoading = false
          new this.$pageModal(
            AddOrUpdateVDefineSelf,
            {
              props: {
                productCode: this.formSearch.productCode,
                tenantCode: _obj.id ? _obj.tenantCode : this.tenantCode,
                currentVsCode: this.formSearch.vsCode,
                vsId: _obj.id ? _obj.id : "",
                vsType: this.formSearch.vsType,
                teantName: this.ownnerTenantName,
                rowList: _obj,
                attributeContext: _obj.attributeContext,
                vsParentCode: this.formSearch.vsParentCode,
                type: this.vsType    //1为独立值集  2为从属值集
              }
            },
            data => {
              data && this.search();
            }
          );
        });
      } else {
        new this.$pageModal(
          AddOrUpdateVDefineSelf,
          {
            props: {
              productCode: this.formSearch.productCode,
              tenantCode: obj.id ? obj.tenantCode : this.tenantCode,
              currentVsCode: this.formSearch.vsCode,
              vsId: obj.id ? obj.id : "",
              vsType: this.formSearch.vsType,
              teantName: this.ownnerTenantName,
              rowList: obj.id ? obj : {},
              attributeContext: obj.attributeContext,
              vsParentCode: this.formSearch.vsParentCode,
              type: this.vsType    //1为独立值集  2为从属值集
            }
          },
          data => {
            data && this.search();
          }
        );
      }
    },
    deleteVDefineSelf() {
      let deleteStr = this.getIdAndVersion();
      if (deleteStr == "") {
        this.$message.error({
          content: this.$t("module.valueSet.selestItems"),
          duration: 3
        });
        return;
      }
      new $confirm(`${this.$t("common.confirmDeletion")}`, this).then(() => {
        $http.post(`${window.RPConfig.setting}/valueset/item/delete`, this.getIdAndVersion()).then(() => {
          this.$message.success({
            content: this.$t("module.valueSet.deleteSuccessfully"),
            duration: 3
          });
          this.search();
        });
      });
    },
    getIdAndVersion() {
      let list = this.$refs["vDefineTable"].getSelectioned() || [];
      let ids = [];
      for (let vs of list) {
        ids.push(vs.id);
      }
      return ids;
    },
    getParentVsColumn() {
      if (this.columnType == "2") {
        return {
          title: this.$t("module.valueSet.parentValue"),
          align: "left",
          key: "vsiParentValue",
          visible: false
        };
      } else {
        return;
      }
    },
    getOperatingCols(row) {
      let operatingCols = [];
      if (this.ownnerTenant == window.RPConfig.rootTenantCode) {
        // vsValueSource等于2， 为可拓展值集，值集项的source等于2，为自建的值集项，可以编辑
        if (this.vsValueSource == 2 && row.source == 2) {
          operatingCols.push({
            type: "icon",
            icon: "md-create",
            text: this.$t("common.edit"),
            handle: () => {
              this.addOrUpdateVDefineSelf(row);
            }
          });
        }
        // 如果可拓展值集的值集项，无效状态可以删除
        if (this.vsValueSource == 2 && row.enabled == 0) {
          operatingCols.push({
            type: "icon",
            icon: "ios-trash",
            text: this.$t("common.delete"),
            handle: () => {
              this.deleted(row.id);
            }
          });
        }
      }
      // 2:如果是租户层:(1):如果是初始化的,只能编辑自己的
      if (this.ownnerTenant != window.RPConfig.rootTenantCode) {
        if (this.tenantId == window.RPConfig.rootTenantCode && this.vsValueSource == 2 && row.tenantCode != window.RPConfig.rootTenantCode) {
          operatingCols.push({
            type: "icon",
            icon: "md-create",
            text: this.$t("common.edit"),
            handle: () => {
              this.addOrUpdateVDefineSelf(row);
            }
          });
          if (row.enabled == 0) {
            operatingCols.push({
              type: "icon",
              icon: "ios-trash",
              text: this.$t("common.delete"),
              handle: () => {
                this.deleted(row.id);
              }
            });
          }
        }
        if (this.source == 2 && this.tenantId != window.RPConfig.rootTenantCode) {
          operatingCols.push({
            type: "icon",
            icon: "md-create",
            text: this.$t("common.edit"),
            handle: () => {
              this.addOrUpdateVDefineSelf(row);
            }
          });
          if (row.enabled == 0) {
            operatingCols.push({
              type: "icon",
              icon: "ios-trash",
              text: this.$t("common.delete"),
              handle: () => {
                this.deleted(row.id);
              }
            });
          }
        }
      }
      return operatingCols;
    }
  },
  watch: {},
  directives: {}
};
</script>
